#!/usr/bin/env python3
# coding:utf-8

from contextlib import asynccontextmanager
from typing import Any
from fastapi import FastAPI
from fastapi_mqtt import FastMQTT, MQTTConfig

# 配置 MQTT
mqtt_config = MQTTConfig()
fast_mqtt = FastMQTT(config=mqtt_config)

# 定义 FastAPI 应用的生命周期管理
@asynccontextmanager
async def _lifespan(_app: FastAPI):
    await fast_mqtt.mqtt_startup()
    yield
    await fast_mqtt.mqtt_shutdown()


app = FastAPI(lifespan=_lifespan)

# 连接回调
@fast_mqtt.on_connect()
def connect(client, flags, rc, properties):
    client.subscribe("/mqtt")  # 订阅 MQTT 主题
    print("Connected: ", client, flags, rc, properties)

# 消息回调
@fast_mqtt.on_message()
async def message(client, topic, payload, qos, properties):
    print("Received message: ", topic, payload.decode(), qos, properties)

# 订阅主题
@fast_mqtt.subscribe("mqtt/+/temperature", "mqtt/+/humidity", qos=1)
async def home_message(client, topic, payload, qos, properties):
    print("temperature/humidity: ", topic, payload.decode(), qos, properties)

# 发布消息
@app.get("/test")
async def func():
    fast_mqtt.publish("/mqtt", "Hello from Fastapi")  # 发布 MQTT 主题
    return {"result": True, "message": "Published"}
